package cn.hxzy.icon.zyinon.controller;

import cn.hxzy.icon.zyinon.entity.User;
import cn.hxzy.icon.zyinon.entity.vo.ReturnBean;
import cn.hxzy.icon.zyinon.service.UserService;
import cn.hxzy.icon.zyinon.util.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class PublicController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public ReturnBean login(String loginName, String loginPassword, HttpSession session) {
        User user = userService.findByLoginNameAndLoginPassword(loginName, loginPassword);
        if (user != null) {
            session.setAttribute("loginUser", user);
            return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, user);
        }
        return ReturnBean.of(ReturnBean.AnswerCode.AUTH_ERROR);
    }

    @PostMapping("userInfo")
    public ReturnBean userInfo(HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return ReturnBean.of(ReturnBean.AnswerCode.NOT_LOGIN);
        }
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS, loginUser);
    }
    @PostMapping("logout")
    public ReturnBean logout(HttpSession session) {
       session.invalidate();
        return ReturnBean.of(ReturnBean.AnswerCode.SUCCESS);
    }

    @GetMapping("verify")
    public void verify(HttpServletRequest request, HttpServletResponse response) {
        VerifyUtil.getRandcode(request, response);
    }
}
